import axios from 'axios'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'

export default function request(config) {
  const instance = axios.create({
    baseURL: 'http://localhost:8888',
    timeout: 5000,
    headers:{
      'Content-Type': 'application/json; charset=UTF-8',
    }
  })

  instance.interceptors.request.use(config => {
    // 展示进度条
    NProgress.start()
    // 设置token
    config.headers.Authorization = window.sessionStorage.getItem('token')
    return config
  })

  instance.interceptors.response.use(res => {
    // 隐藏进度条
    NProgress.done()
    // 响应码不是2xx，展示错误信息
    if (res.status !== 200) {
      Message.error(res.code)
    }
    if(res.data.code !== 200){
      Message.error(res.data.msg)
      switch (res.data.code) { 
        case 10003:   
        case 90002: 
          router.push('/login') 
          break 
      }
    }
    // Message.success(res.status)
    return res.data
  }
  , err => { 
    // 隐藏进度条
    NProgress.done() 
    switch (err.response.status) {
      case 400:
        Message.error('请求参数错误')
        break
      case 401:
        Message.error('未授权')
        break
      case 403:
        Message.error('禁止访问')
        break
      case 404:
        Message.error('请求资源不存在')
        break
      case 500:
        Message.error('服务器内部错误')
        break
      default:
        Message.error('未知错误')
        break
    }
  })
  return instance(config)
}